﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using GameProtocol;
using Google.Protobuf;
using UnityMultiPlayerGameServer.Clients;

namespace UnityMultiPlayerGameServer.Data
{
    internal class Message
    {
        public byte[] buffer = new byte[1024];

        public int startIndex = 0;

        public void ReadBuffer(int length, Client client, Action<GamePack, Client> PackHandel)
        {
            startIndex += length;
            while (true)
            {
                if (startIndex <= 4) return;
                //实际消息体长度
                int count = BitConverter.ToInt32(buffer, 0);
                if (startIndex >= (count + 4))
                {
                    GamePack pack = (GamePack)GamePack.Descriptor.Parser.ParseFrom(buffer, 4, count);                 
                    //处理包
                    PackHandel(pack, client);
                    //Console.WriteLine(pack.TestString);

                    //若处理完这条消息后，数组中还有数据，则移动其至数组前面
                    Array.Copy(buffer, count + 4, buffer, 0, startIndex - count - 4);
                    startIndex -= (count + 4);
                }
                else
                {
                    break;
                }
            }
        }

        public static byte[] PackData(GamePack pack)
        {
            byte[] data = pack.ToByteArray();//包体
            byte[] head = BitConverter.GetBytes(data.Length);//包头
            return head.Concat(data).ToArray();
        }

        public static Byte[] PackData_UDP(GamePack pack)
        {
            return pack.ToByteArray();
        }
    }
}
